package top.laoshuzi.android.iotcamera.core.network.utils

import com.blankj.utilcode.util.DeviceUtils
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttMessage
import top.laoshuzi.android.iotcamera.core.network.config.MqttConfig
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import java.nio.charset.StandardCharsets.US_ASCII


/**
 * Created by mouse on 2018/2/1.
 */

object MqttUtils {

    fun mqttClient(): MqttClient {
        return MqttClient(MqttConfig.MQTT_URL, DeviceUtils.getAndroidID(), MemoryPersistence())
    }

    fun mqttConfig(): MqttConnectOptions {
        return MqttConnectOptions().apply {
            userName = MqttConfig.USERNAME
            password = MqttConfig.PASSWORD.toCharArray()
            connectionTimeout = MqttConfig.CONNECT_TIMEOUT
            keepAliveInterval = MqttConfig.KEEP_ALIVE_INTERVAL
            isAutomaticReconnect = true
            isCleanSession = true
        }
    }

    fun mqttPayload(mqttMessage: MqttMessage): String {
        return String(mqttMessage.payload, US_ASCII)
    }

    fun mqttMessage(payload: String, qos: Int, retained: Boolean): MqttMessage {
        return mqttMessage(payload.toByteArray(US_ASCII), qos, retained)
    }

    fun mqttMessage(payload: ByteArray, qos: Int, retained: Boolean): MqttMessage {
        return MqttMessage().apply {
            this.payload = payload
            this.qos = qos
            this.isRetained = retained
        }
    }

}


